﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Swashbuckle.AspNetCore;
using Swashbuckle.AspNetCore.Swagger;
using Microsoft.Extensions.PlatformAbstractions;
using System.IO;
using System.Security.Cryptography;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using System.IdentityModel.Tokens.Jwt;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Authentication;
using Elight.Infrastructure.Settings;
using Elight.Infrastructure.Ioc;
using Elight.WebApi.Extensions;
using Elight.WebApi.Filters;

namespace Elight.WebApi
{
    /// <summary>
    /// 程序启动配置类。
    /// </summary>
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        /// <summary>
        /// 配置读取接口。
        /// </summary>
        public IConfiguration Configuration { get; }

        /// <summary>
        /// 该方法在程序启动时被调用，使用此方法为容器注册服务。
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddOptions();

            services.Configure<AppSettings>(Configuration);

            ConfigureSwagger(services);

            ConfigureJwtAuth(services);

            services.RegisterServices();

            services.RegisterRepositories();

            services.AddMemoryCache();

            services.AddMvc(c =>
            {
                c.Filters.Add<ExceptionHandlingAttribute>();
            });

            services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
            {
                builder.AllowAnyOrigin()
                       .AllowAnyMethod()
                       .AllowAnyHeader();
            }));
        }

        /// <summary>
        /// 该方法在程序启动时被调用，使用此方法来配置HTTP请求管道。
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/error");
            }

            app.UseStaticFiles();

            app.UseStatusCodePages();

            app.UseSwagger();

            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "ELIGHT API V1");
            });

            app.UseAuthentication();

            app.UseMvc();

            ServiceLocator.ServiceProvider = app.ApplicationServices;
        }

        /// <summary>
        /// 配置授权认证（Json Web Token）信息。
        /// </summary>
        /// <param name="services"></param>
        private void ConfigureJwtAuth(IServiceCollection services)
        {
            var audienceConfig = Configuration.GetSection("Jwt");
            var symmetricKeyAsBase64 = audienceConfig["Secret"];
            var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64);
            var signingKey = new SymmetricSecurityKey(keyByteArray);

            var tokenValidationParameters = new TokenValidationParameters
            {
                // The signing key must match!  
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = signingKey,

                // Validate the JWT Issuer (iss) claim  
                ValidateIssuer = true,
                ValidIssuer = audienceConfig["Issuer"],

                // Validate the JWT Audience (aud) claim 
                ValidateAudience = true,
                ValidAudience = audienceConfig["Audience"],

                // Validate the token expiry 
                ValidateLifetime = true,

                ClockSkew = TimeSpan.Zero
            };

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(o =>
            {
                o.IncludeErrorDetails = true;
                o.TokenValidationParameters = tokenValidationParameters;
                o.Events = new JwtBearerEvents()
                {
                    OnAuthenticationFailed = c =>
                    {
                        c.NoResult();
                        c.Response.StatusCode = 401;
                        c.Response.ContentType = "text/plain";
                        return c.Response.WriteAsync(c.Exception.ToString());
                    }
                };
            });
        }

        /// <summary>
        /// 配置在线接口文档（Swagger）信息。
        /// </summary>
        /// <param name="services"></param>
        private void ConfigureSwagger(IServiceCollection services)
        {
            var swaggerConfig = Configuration.GetSection("SwaggerDoc");

            //Register the Swagger generator, defining one or more Swagger documents.
            services.AddSwaggerGen(option =>
            {
                option.SwaggerDoc(swaggerConfig["Name"], new Info()
                {
                    Title = swaggerConfig["Info:Title"],
                    Description = swaggerConfig["Info:Description"],
                    Version = swaggerConfig["Info:Version"],
                    Contact = new Contact()
                    {
                        Name = swaggerConfig["Info:Contact:Name"],
                        Email = swaggerConfig["Info:Contact:Email"],
                        Url = swaggerConfig["Info:Contact:Url"]
                    },
                    License = new License()
                    {
                        Name = swaggerConfig["Info:License:Name"],
                        Url = swaggerConfig["Info:License:Url"]
                    }
                });

                //// Set the comments path for the Swagger JSON and UI.
                //var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                //var xmlPath = Path.Combine(basePath, "Elight.WebApi.xml");
                //c.IncludeXmlComments(xmlPath);
            });
        }
    }

}
